package neu.soft.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import neu.soft.constant.FinancialVoucherType;
import neu.soft.entity.FinancialVoucher;
import neu.soft.exception.AppException;
import neu.soft.exception.AppExceptionCodeMsg;
import neu.soft.mapper.FinancialVoucherMapper;
import neu.soft.query.BasePageQuery;
import neu.soft.service.FinancialVoucherService;
import neu.soft.util.TypeConvert;
import neu.soft.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 李博
 * 财务凭证服务
 */
@Service
public class FinancialVoucherServiceImpl implements FinancialVoucherService {

    @Autowired
    FinancialVoucherMapper financialVoucherMapper;

    @Override
    public void addFinancialVoucher(FinancialVoucher financialVoucher) {

        if (financialVoucher == null){
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }
        int res = financialVoucherMapper.addFinancialVoucher(financialVoucher);
        if (res < 1){
            throw new AppException(AppExceptionCodeMsg.DZYJ_NGDZ);
        }
    }

    @Override
    public FinancialVoucher findById(Integer voucherId) {
        return financialVoucherMapper.findById(voucherId);
    }

    @Override
    public FinancialVoucher findByOrderId(String orderId) {
        return financialVoucherMapper.findByOrderId(orderId);
    }

    @Override
    public PageBean<FinancialVoucher> findByPage(BasePageQuery query) {

        PageBean<FinancialVoucher> pageBean = new PageBean<>();
        PageHelper.startPage(query.getPageNow(), query.getPageSize());
        List<FinancialVoucher> financialVoucherList = financialVoucherMapper.findByPage(query);
        financialVoucherList.forEach(financialVoucher -> {
            String type = TypeConvert.enumToString(FinancialVoucherType.class,financialVoucher.getVoucherType());
            financialVoucher.setVoucherType(type);
        });
        PageInfo<FinancialVoucher> pageInfo = new PageInfo<>(financialVoucherList);
        pageBean.setTotalRows(pageInfo.getTotal());
        pageBean.setTotalPages(pageInfo.getPages());
        pageBean.setRowData(pageInfo.getList());
        return pageBean;
    }

    @Override
    public void updateVoucher(FinancialVoucher financialVoucher) {
        int res = financialVoucherMapper.update(financialVoucher);
        if (res < 1){
            throw new AppException(AppExceptionCodeMsg.YYDZ_JDWGXSB);
        }
    }
}
